package com.sj.parksdk.fragment.main;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ruffian.library.widget.RTextView;
import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.adapter.carmanage.AdapterCarColorSelect;
import com.sj.parksdk.adapter.carmanage.AdapterCarLetter;
import com.sj.parksdk.adapter.carmanage.AdapterCarNumberGridAdapter;
import com.sj.parksdk.adapter.carmanage.FlowAdapterCarNumber;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.core.http.subscriber.TipRequestSubscriber;
import com.sj.parksdk.net.base.CommonResult;
import com.sj.parksdk.net.http.ApiHelper;
import com.sj.parksdk.net.http.MyNetApi;
import com.sj.parksdk.setting.Dictionary;
import com.sj.parksdk.setting.Extras;
import com.sj.parksdk.utils.Utils;
import com.sj.parksdk.utils.XToastUtils;
import com.sj.parksdk.widget.sweetalert.SweetAlertDialog;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.layout.ExpandableLayout;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xutil.common.StringUtils;

import java.util.Arrays;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

@Page(name = "添加车辆")
public class FragmentAddCar extends BaseFragment {
    @BindView(R2.id.recycler_grid)
    RecyclerView recyclerGrid;
    @BindView(R2.id.btn_submit)
    SuperButton btnSubmit;
    @BindView(R2.id.rtv_pay)
    RTextView rtvPay;
    @BindView(R2.id.ll_up_or_down)
    LinearLayout llUpOrDown;
    @BindView(R2.id.ll_soft_input)
    ExpandableLayout llSoftInput;
    @BindView(R2.id.recycler_type)
    RecyclerView recyclerType;
    @BindView(R2.id.recycler_letter)
    RecyclerView recyclerLetter;
    @BindView(R2.id.flow_number)
    RecyclerView flowNumber;
    @BindView(R2.id.ll_softinput_number)
    LinearLayout llSoftinputNumber;
    @BindView(R2.id.recycler_canton)
    RecyclerView recyclerCanton;
    @BindView(R2.id.recycler_canton2)
    RecyclerView recyclerCanton2;
    @BindView(R2.id.ll_softinput_canton)
    LinearLayout llSoftinputCanton;
    @BindView(R2.id.tv_error_tip)
    TextView tvErrorTip;

    private boolean softIsShown = true;

    private AdapterCarNumberGridAdapter gridAdapter;
    private int currentPosition = 0;//当前编辑项游标

    private String[] number;

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_fragment_add_car;
    }

    @Override
    protected void initViews() {
        rtvPay.setSelected(true);
        initRecycler();
    }

    private void initRecycler() {

        initGrid();

        initCantonSoftInput();

        initLetterSoftInput();
    }

    /**
     * 输入的车牌号
     */
    private void initGrid() {
        number = new String[]{"苏", "", "", "", "", "", "", ""};
        WidgetUtils.initGridRecyclerView(recyclerGrid, 8, DensityUtils.dp2px(8));
        gridAdapter = new AdapterCarNumberGridAdapter();
        recyclerGrid.setAdapter(gridAdapter);
        gridAdapter.refresh(number);
        gridAdapter.setOnItemClickListener((itemView, item, position) -> onItemGridSelected(position));
        gridAdapter.setSelectPosition(currentPosition);
    }

    /**
     * 编辑选中项
     */
    private void onItemGridSelected(int position) {
        gridAdapter.setSelectPosition(position);
        currentPosition = position;
        showSoftInput();
        if (!softIsShown) {
            llSoftInput.expand();
            softIsShown = true;
        }
    }

    /**
     * 显示软键盘内容
     */
    private void showSoftInput() {
        if (currentPosition == 0) showCantonSoftInput();
        else showLetterSoftInput();
    }

    /**
     * 显示行政区选项
     */
    private void showCantonSoftInput() {
        llSoftinputCanton.setVisibility(View.VISIBLE);
        llSoftinputNumber.setVisibility(View.GONE);
    }

    /**
     * 显示号码选项
     */
    private void showLetterSoftInput() {
        llSoftinputNumber.setVisibility(View.VISIBLE);
        llSoftinputCanton.setVisibility(View.GONE);
    }

    private void initCantonSoftInput() {

        String[] canton = ResUtils.getStringArray(R.array.park_add_car_canton);
        WidgetUtils.initGridRecyclerView(recyclerCanton, 7, 0);
        AdapterCarLetter adapterCanton = new AdapterCarLetter(canton);
        recyclerCanton.setAdapter(adapterCanton);
        adapterCanton.setOnItemClickListener((itemView, item, position) -> inputSelection(item));

        String[] canton2 = ResUtils.getStringArray(R.array.park_add_car_canton2);
        WidgetUtils.initGridRecyclerView(recyclerCanton2, 5, 0);
        AdapterCarLetter adapterCanton2 = new AdapterCarLetter(canton2);
        recyclerCanton2.setAdapter(adapterCanton2);
        adapterCanton2.setOnItemClickListener((itemView, item, position) -> inputSelection(item));
    }

    private void initLetterSoftInput() {
        String[] number = ResUtils.getStringArray(R.array.park_add_car_number);
        FlowAdapterCarNumber tagAdapter = new FlowAdapterCarNumber(number);
        flowNumber.setLayoutManager(Utils.getFlexboxLayoutManager(getContext()));
        flowNumber.setAdapter(tagAdapter);
        tagAdapter.setOnItemClickListener((itemView, item, position) -> inputSelection(item));

        String[] letter = ResUtils.getStringArray(R.array.park_add_car_letter);
        WidgetUtils.initGridRecyclerView(recyclerLetter, 7, 0);
        AdapterCarLetter adapterLetter = new AdapterCarLetter(letter);
        recyclerLetter.setAdapter(adapterLetter);
        adapterLetter.setOnItemClickListener((itemView, item, position) -> inputSelection(item));

        String[] type = ResUtils.getStringArray(R.array.park_add_car_type);
        WidgetUtils.initGridRecyclerView(recyclerType, 6, 0);
        AdapterCarLetter adapterType = new AdapterCarLetter(type);
        adapterType.setLetterType("type");
        recyclerType.setAdapter(adapterType);
        adapterType.setOnItemClickListener((itemView, item, position) -> inputSelection(item));
    }

    /**
     * 输入选项
     *
     * @param str
     */
    private void inputSelection(String str) {
        if (StringUtils.isEmpty(str)) return;
        if ("I".equals(str) || "O".equals(str)) return;
        if ("-1".equals(str)) {
            deleteAndBack();
            return;
        }
        inputAndNext(str);
    }

    private void deleteAndBack() {
        number[currentPosition] = "";
        gridAdapter.refresh(number);
        if (currentPosition == 0) {
            gridAdapter.setSelectPosition(currentPosition);
            return;
        }
        onItemGridSelected(currentPosition - 1);
    }

    private void inputAndNext(String str) {
        number[currentPosition] = str;
        gridAdapter.refresh(number);
        if (currentPosition == number.length - 1) {
            gridAdapter.setSelectPosition(currentPosition);
            return;
        }
        onItemGridSelected(currentPosition + 1);
    }

    @OnClick({R2.id.btn_submit
            , R2.id.rtv_pay
            , R2.id.ll_up_or_down
            , R2.id.rl_back
    })
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_submit) {
            if (checkLogin() && checkData()) {
                swtichPlateCorlors();
            }
        } else if (id == R.id.rtv_pay) {
            rtvPay.setSelected(!rtvPay.isSelected());
        } else if (id == R.id.ll_up_or_down) {
            hideOrShowSoftInput();
        } else if (id == R.id.rl_back) {
            deleteAndBack();
        }
    }

    private void swtichPlateCorlors() {
        StringBuffer sb = new StringBuffer();
        for (String s : number) {
            sb.append(s);
        }
        String carNumber = sb.toString();
        String plateColor = Dictionary.getPalteColorWithNumber(number);
        if (Dictionary.Car.PlateColor.Unknow.equals(plateColor)) {
            showColorSelectDialog(carNumber);
            return;
        }
        addCar(carNumber, plateColor, null);
    }

    private boolean checkData() {
        boolean check = true;
        for (int i = 0; i < number.length - 1; i++) {
            if (StringUtils.isEmpty(number[i])) {
                check = false;
                break;
            }
        }
        tvErrorTip.setText(check?"":"车牌号错误，请重新输入");
        return check;
    }

    private String[] arrColor = ResUtils.getStringArray(R.array.park_car_colors);
    private AdapterCarColorSelect adapterColor;

    private void showColorSelectDialog(String carNumber) {
        adapterColor = new AdapterCarColorSelect(Arrays.asList(arrColor));
        LinearLayoutManager lm = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        adapterColor.setmOnItemClickListener((position, name) -> selectedCarColor(adapterColor, position));
        new SweetAlertDialog(getContext(), SweetAlertDialog.RECYCLER_TYPE)
                .setContentMinHeight(DensityUtils.dp2px(200))
                .setTitleText("请选择车牌颜色")
                .setContentText(null)
                .setRecyclerAdapter(adapterColor, lm)
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {

                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        addCar(carNumber, arrColor[adapterColor.getSelectedPosition()], sDialog);
                    }
                })
                .show();
    }


    private void addCar(String carNumber, String plateColor, SweetAlertDialog sDialog) {
        if (sDialog != null) {
            sDialog.setTitleGone(true)
                    .setContentText(null)
                    .setCancelable(false);
            sDialog.changeAlertType(SweetAlertDialog.PROGRESS_TYPE);
        } else {
            sDialog = new SweetAlertDialog(getContext(), SweetAlertDialog.PROGRESS_TYPE)
                    .setContentMinHeight(DensityUtils.dp2px(200))
                    .setTitleGone(true)
                    .setContentText(null);
            sDialog.setCancelable(false);
            sDialog.show();
        }
        addCarRequest(carNumber, plateColor, sDialog);
    }

    @SuppressLint("CheckResult")
    private void addCarRequest(String carNumber, String plateColor, SweetAlertDialog sDialog) {
        CustomRequest request = XHttp.custom();
        request.call(ApiHelper.getInstance(request)
                .addCar(new MyNetApi.CarAdd(carNumber, plateColor)))
                .subscribeWith(new TipRequestSubscriber<CommonResult>() {
                    @Override
                    protected void onSuccess(CommonResult result) {
                        addCarSuccess(result, sDialog);
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        if (sDialog != null) sDialog.dismiss();
                    }
                });
    }

    private void addCarSuccess(CommonResult result, SweetAlertDialog sDialog) {
        if (result.getCode() != 200) {
            XToastUtils.error(result.getMessage());
            return;
        }
        if (sDialog != null) {
            sDialog.setTitleGone(true)
                    .setContentText("添加成功")
                    .setConfirmText("返回")
                    .showCancelButton(false)
                    .setCancelClickListener(null)
                    .setConfirmClickListener(backDialogListener)
                    .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
        } else {
            new SweetAlertDialog(getContext(), SweetAlertDialog.SUCCESS_TYPE)
                    .setContentMinHeight(DensityUtils.dp2px(200))
                    .setTitleGone(true)
                    .setContentText("添加成功")
                    .setConfirmText("返回")
                    .showCancelButton(false)
                    .setCancelClickListener(null)
                    .setConfirmClickListener(backDialogListener)
                    .show();
        }

    }

    private SweetAlertDialog.OnSweetClickListener backDialogListener = new SweetAlertDialog.OnSweetClickListener() {

        @Override
        public void onClick(SweetAlertDialog sweetAlertDialog) {
            sweetAlertDialog.dismiss();
            Intent intent = new Intent();
            intent.putExtra(Extras.CAR_ADD_CAR, true);
            setFragmentResult(RESULT_OK, intent);
            popToBack();
        }
    };

    private void selectedCarColor(AdapterCarColorSelect adapter, int position) {
        adapter.setSelectedPosition(position);
        adapter.notifyDataSetChanged();
    }

    private void hideOrShowSoftInput() {
        if (softIsShown) {
            llSoftInput.collapse();
            softIsShown = false;
        } else {
            llSoftInput.expand();
            softIsShown = true;
        }
    }

}
